#include <openssl/aes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rand.h>

void usage() {
    printf("\n\nusage: ./AES_decrypt [Source (Ciphertext)] [Key File Name] [Destination (Recovered)] \n");
}


unsigned char iv[16];
unsigned char key[16];

size_t len = 16;


int main(int argc, char *argv[]){  

	if(argc != 4) {
        	usage();
        	exit(1);
    	}

	char *Source;
	char *KeyF;
	char *Destination;	

	Source      = argv[1];
	KeyF 	    = argv[2];
	Destination = argv[3];

	FILE *KEYFILE = fopen(KeyF, "r");

	fread(key, 1, 16, KEYFILE);
printf("CP\n");
	printf("read key is: %s\n", key);

	AES_KEY dekey;

	AES_set_decrypt_key(key, 128, &dekey);

	FILE *Ciphertext = fopen(Source, "r");

	fseek(Ciphertext, 0L, SEEK_END);
	int CiphertextSize = ftell(Ciphertext);
	fseek(Ciphertext, 0L, SEEK_SET);

	unsigned char aux[CiphertextSize];
	unsigned char ciphertext[CiphertextSize - 16];
	unsigned char recoveredtext[CiphertextSize];

	int read = fread(aux, 1, CiphertextSize, Ciphertext);

	printf("ciphertext detected size (+iv): %d\n", CiphertextSize);
	printf("ciphertext read size (+iv): %d\n", read);
	
	memcpy(iv, aux, 16);
	memcpy(ciphertext, aux+16, sizeof(aux)-16);

	AES_cbc_encrypt(ciphertext, recoveredtext, sizeof(ciphertext), &dekey, iv, AES_DECRYPT);
	
	FILE *Recoveredtext = fopen(Destination, "w");
	fwrite(recoveredtext, 1, sizeof(recoveredtext), Recoveredtext);

	fclose(Ciphertext);
	fclose(Recoveredtext);

	return 0;
}


